import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

class Student{
    public int studentId;
    public int classId;
}
@WebServlet("/PostParameter2")
public class PostParameter2 extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过这个方法来处理 body 的json格式的数据
        //直接把req对象里 body 完整的读取出来
        //getInputStream
//第一种: 获取body中的全部
/*        int length = req.getContentLength();
        byte[] buffer = new byte[length];

        InputStream inputStream = req.getInputStream();
        inputStream.read(buffer);

        String body = new String(buffer);
        System.out.println("body = "+body);
        resp.getWriter().write(body);*/

//第二种:通过第三方库 jackson来 获取键值对
        //使用jackson使用的对象
        ObjectMapper objectMapper = new ObjectMapper();
        //1.会从body中读取中json格式的字符串
        //2.根据第二个参数类对象,创建student实例
        //3.解析上述json格式的字符串,处理成map键值对结构
        //4.遍历所有键值对, 看键的名字和 student 实例的那个属性名字匹配,就对应的value设置到该属性中
        //5.返回该student实例
        Student student = objectMapper.readValue(req.getInputStream(), Student.class);
        System.out.println(student.studentId+","+ student.classId);
        resp.getWriter().write(student.studentId+","+ student.classId);



    }
}
